<script lang="ts" setup>
import { useImStore } from "@/stores/modules/im";
import { reactive, computed, toRefs, ref } from "vue";
import { EMClient } from "@/IM";
import { MESSAGE_TYPE } from "@/IM/constant";
import BenzAMRRecorder from "benz-amr-recorder";
import fileSizeFormat from "../../utils/fileSizeFormat";
import dateFormat from "../../utils/dateFormater";
import { CUSTOM_MESSAGE_TYPE } from "../../constant";
import { emojis } from "../suit/emoji.js";
import { ElMessage, ElMessageBox } from "element-plus";
import mapBox from "./mapBox.vue";
const props = defineProps({
  messageData: {
    type: [Array, Object],
    default: () => {
      return [];
    }
  },
  toUserInfo: {
    type: [Array, Object],
    default: () => {
      return {};
    }
  },
  customData: {
    type: [Array, Object],
    default: () => {
      return {};
    }
  },
  loading: {
    type: Boolean,
    default: true
  }
});
const { messageData } = toRefs(props);
const isMyself = computed(() => {
  return msgBody => {
    return msgBody.from === EMClient.user;
  };
});
const imStore = useImStore();
const loginUserInfo: any = imStore.userInfo;

const handleStatusShow = computed(() => {
  return id => {
    return imStore.messageStates[id] == 0
      ? "msgStatus1"
      : imStore.messageStates[id] == 1
        ? "msgStatus2"
        : imStore.messageStates[id] == 2
          ? "msgStatus3"
          : imStore.messageStates[id] == 3
            ? "msgStatus4"
            : "";
  };
});

const handleMsgTimeShow = computed(() => {
  let msgList: any[] = Array.from(messageData.value);
  return (time, index) => {
    if (index !== 0) {
      const lastTime = msgList[index - 1].time;
      return time - lastTime > 50000 ? dateFormat("MM/DD/HH:mm", time) : false;
    } else {
      return dateFormat("MM/DD/HH:mm", time);
    }
  };
});

//音频播放状态
const audioPlayStatus = reactive({
  isPlaying: false, //是否在播放中
  playMsgId: "" //在播放的音频消息id,
});
//开始播放
const startplayAudio = msgBody => {
  const armRec = new BenzAMRRecorder();
  const src = msgBody.url;
  audioPlayStatus.playMsgId = msgBody.id;

  //初始化音频源并调用播放
  armRec.initWithUrl(src).then(() => {
    if (!audioPlayStatus.isPlaying) {
      armRec.play();
    }
  });
  //播放开始监听
  armRec.onPlay(() => {
    audioPlayStatus.isPlaying = true;
    audioPlayStatus.playMsgId = msgBody.id;
  });
  //播放结束监听
  armRec.onStop(() => {
    audioPlayStatus.isPlaying = false;
    audioPlayStatus.playMsgId = "";
  });
};
const getTxtMsgSplit = (str: any) => {
  const regex = /\[(.*?)\]/g;
  const matches: any = [];
  let lastIndex = 0;
  let match;
  while ((match = regex.exec(str)) !== null) {
    const emoji = "[" + match[1] + "]";
    if (lastIndex < match.index) {
      matches.push(str.substring(lastIndex, match.index));
    }
    matches.push(emoji);
    lastIndex = regex.lastIndex;
  }
  if (lastIndex < str.length) {
    matches.push(str.substring(lastIndex));
  }
  return matches;
};
const emojiObj = emojis.maps;
const emojiPath = emojis.path;

//撤回消息
const callBackMsg = async msgBody => {
  try {
    await ElMessageBox.confirm("确认要撤回这条消息吗？", "消息撤回", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });
    EMClient.recallMessage({
      mid: msgBody.id,
      to: msgBody.to,
      chatType: "singleChat",
      ext: "callBack"
    })
      .then(res => {
        imStore.deleteAmessage(msgBody, false);
        ElMessage({
          type: "success",
          message: "消息已撤回",
          center: true
        });
      })
      .catch(err => {
        ElMessage({
          type: "error",
          message: "撤回失败",
          center: true
        });
      });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage({
        type: "error",
        message: "撤回失败",
        center: true
      });
    }
  }
};
//删除消息
const deleteMsg = async msgBody => {
  try {
    await ElMessageBox.confirm("确认要删除这条消息吗？", "消息删除", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });
    EMClient.removeHistoryMessages({
      targetId: msgBody.to === imStore.chatWith ? msgBody.to : msgBody.from,
      chatType: "singleChat",
      messageIds: [msgBody.id]
    })
      .then(res => {
        imStore.deleteAmessage(msgBody, false);
        ElMessage({
          type: "success",
          message: "消息已删除",
          center: true
        });
      })
      .catch(err => {
        ElMessage({
          type: "error",
          message: "删除失败",
          center: true
        });
      });
  } catch (error) {
    if (error !== "cancel") {
      ElMessage({
        type: "error",
        message: "删除失败",
        center: true
      });
    }
  }
};

//议价弹窗
import sendDicker from "../suit/sendDicker.vue";
const dickerComp = ref<any>(null);
const sendDickerDialogOpen = (val, title) => {
  console.log(val, title);
  dickerComp.value.showDickerDialog(val, title);
};
const callBackTime = msgBody => {
  if (new Date().getTime() - msgBody.time > 120000) {
    return false;
  } else if (msgBody.from === EMClient.user) {
    return true;
  } else {
    return false;
  }
};
</script>
<template>
  <!-- 议价 -->
  <sendDicker ref="dickerComp"></sendDicker>
  <div>
    <div class="messageList_box" v-for="(msgBody, index) in messageData" :key="msgBody.id" :data-mid="msgBody.id">
      <!-- 普通消息气泡 -->
      <template v-if="!msgBody.isRecall && msgBody.type !== CUSTOM_MESSAGE_TYPE.INFORM">
        <div
          class="message_box_item"
          :style="{
            flexDirection: isMyself(msgBody) ? 'row-reverse' : 'row'
          }"
        >
          <div class="message_item_time">
            {{ handleMsgTimeShow(msgBody.time, index) || "" }}
          </div>
          <el-avatar
            class="message_item_avator"
            :src="
              isMyself(msgBody)
                ? loginUserInfo?.avator
                  ? loginUserInfo?.avator
                  : 'https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/message/theme2x.png'
                : toUserInfo?.avator
                  ? toUserInfo?.avator
                  : 'https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/message/theme22x.png'
            "
          >
          </el-avatar>
          <!-- 普通消息内容 -->
          <div class="message_box_card">
            <!-- 点击消息的下拉操作 -->
            <el-dropdown
              class="message_box_content"
              :class="[
                isMyself(msgBody) ? 'message_box_content_mine' : 'message_box_content_other',
                msgBody.ext === 'callBack' ? 'noneBg' : ''
              ]"
              trigger="contextmenu"
              placement="bottom-end"
            >
              <div>
                <!-- 消息状态展示 -->
                <div class="message_item_status" v-if="imStore.messageStates[msgBody.id]">
                  <img class="message_item_readed_icon" :src="'https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/icon/'+handleStatusShow(msgBody.id)+'.png'" title="消息已读" />
                </div>

                <!-- 文本类型消息 -->
                <div v-if="msgBody.type === MESSAGE_TYPE.TEXT" class="txtMsgContent">
                  <span v-for="(d_item, d_index) in getTxtMsgSplit(msgBody.msg)" :key="d_index + d_item" class="txtSpan">
                    <text v-if="!emojiObj[d_item]" class="txtMsg">{{ d_item }}</text>
                    <el-image v-else :src="emojiPath + emojiObj[d_item]" class="emojiPng" fit="cover" />
                  </span>
                </div>
                <!-- 图片类型消息 -->
                <el-image
                  v-if="msgBody.type === MESSAGE_TYPE.IMAGE"
                  style="max-width: 200px; border-radius: 5px"
                  :src="msgBody.thumb"
                  :preview-src-list="[msgBody.url]"
                  :initial-index="1"
                  fit="cover"
                />
                <!-- 视频类型消息 -->
                <div v-if="msgBody.type === MESSAGE_TYPE.VIDEO" class="videoContent">
                  <video
                    :src="msgBody.url"
                    :poster="msgBody.thumb"
                    style="width: 100%; max-width: 400px; height: 100%; border-radius: 5px"
                    controls
                  ></video>
                </div>
                <!-- 语音类型消息 -->
                <div
                  :class="[
                    'message_box_content_audio',
                    isMyself(msgBody) ? 'message_box_content_audio_mine' : 'message_box_content_audio_other'
                  ]"
                  v-if="msgBody.type === MESSAGE_TYPE.AUDIO"
                  @click="startplayAudio(msgBody)"
                  :style="`width:${msgBody.length * 10}px`"
                >
                  <span class="audio_length_text"> {{ msgBody.length }}′′ </span>
                  <div
                    :class="[
                      isMyself(msgBody) ? 'play_audio_icon_mine' : 'play_audio_icon_other',
                      audioPlayStatus.playMsgId === msgBody.id && 'start_play_audio'
                    ]"
                    style="background-size: 100% 100%"
                  ></div>
                </div>
                <!-- 位置消息 -->
                <div v-if="msgBody.type === MESSAGE_TYPE.LOCATION">
                  <mapBox :msgBody="msgBody"></mapBox>
                </div>
                <div v-if="msgBody.ext === 'callBack'" class="callBack">
                  {{ isMyself(msgBody) ? "您" : "对方" }}撤回了一条消息
                </div>
                <!-- 文件类型消息 -->
                <div v-if="msgBody.type === MESSAGE_TYPE.FILE" class="message_box_content_file">
                  <div class="file_text_box">
                    <div class="file_name">
                      {{ msgBody.filename }}
                    </div>
                    <div class="file_size">
                      {{ fileSizeFormat(msgBody.file_length) }}
                    </div>
                    <a class="file_download" :href="msgBody.url" download>点击下载</a>
                  </div>
                  <span class="iconfont icon-wenjian"></span>
                </div>
                <!-- 自定义类型消息 -->
                <div
                  v-if="msgBody.customExts?.type == 'dicker' && msgBody.type === MESSAGE_TYPE.CUSTOM"
                  class="message_box_content_custom"
                >
                  <div class="type">岗位议价</div>
                  <div class="content">
                    <div class="title">
                      <div>{{ msgBody?.customExts.info }}</div>
                      <div class="price">{{ msgBody.customExts.price }}元</div>
                    </div>
                    <el-button
                      type="primary"
                      class="operateBtn"
                      @click="sendDickerDialogOpen(msgBody.customExts.price, msgBody.customExts.info)"
                      >回复价格</el-button
                    >
                  </div>
                </div>
                <div
                  v-if="
                    msgBody.customExts?.type != 'dicker' &&
                    msgBody.type === MESSAGE_TYPE.CUSTOM &&
                    loading &&
                    !customData[msgBody.customExts.id]
                  "
                  class="message_box_content_custom"
                >
                  数据加载中
                </div>
                <div
                  v-if="msgBody.type === MESSAGE_TYPE.CUSTOM && msgBody.customExts?.type != 'dicker'&& (!loading || customData[msgBody.customExts.id])"
                  class="message_box_content_custom"
                >
                  <div class="type" v-if="msgBody.customExts?.type != 'dicker'">
                    {{
                      msgBody.customExts.type == "flexJob"
                        ? "零工岗位"
                        : msgBody.customExts.type == "job"
                          ? "全职岗位"
                          : msgBody.customExts.type == "interview"
                            ? "面试邀请"
                            : ""
                    }}
                    <div
                      class="btn"
                      v-if="msgBody.customExts.type == 'interview' && customData[msgBody.customExts.id]"
                      :class="'btn' + customData[msgBody.customExts.id].interviewStatus"
                    >
                      {{
                        customData[msgBody.customExts.id].interviewStatus == 1
                          ? "待接受"
                          : customData[msgBody.customExts.id].interviewStatus == 2
                            ? "已接受"
                            : "已拒绝"
                      }}
                    </div>
                  </div>
                  <div class="content" v-if="msgBody.customExts.type == 'interview' && customData[msgBody.customExts.id]">
                    <div class="item">
                      <div class="label">面试时间:</div>
                      <div class="info">{{ customData[msgBody.customExts.id].interviewDate }}</div>
                    </div>
                    <div class="item">
                      <div class="label">面试职位:</div>
                      <div class="info">{{ customData[msgBody.customExts.id].jobName }}</div>
                    </div>
                    <div class="item">
                      <div class="label">联系方式:</div>
                      <div class="info">
                        {{ customData[msgBody.customExts.id].contactor }}{{ customData[msgBody.customExts.id].contactPhone }}
                      </div>
                    </div>
                    <div class="item">
                      <div class="label">面试地址:</div>
                      <div class="info">{{ customData[msgBody.customExts.id].address }}</div>
                    </div>
                  </div>
                  <div class="content" v-if="msgBody.customExts.type == 'job'">
                    <div class="title">
                      <div>{{ customData[msgBody.customExts.id]?.title }}</div>
                      <div class="price">
                        {{ customData[msgBody.customExts.id]?.priceStart }}-{{ customData[msgBody.customExts.id]?.priceEnd }}元/月
                      </div>
                    </div>
                    <div class="typeName">{{ customData[msgBody.customExts.id]?.typeName }}</div>
                    <div class="info">{{ customData[msgBody.customExts.id]?.content }}</div>
                  </div>
                  <div class="content" v-if="msgBody.customExts.type == 'flexJob'">
                    <div class="title">
                      <div>{{ customData[msgBody.customExts.id]?.title }}</div>
                      <div class="price">{{ customData[msgBody.customExts.id]?.priceAmt }}元</div>
                    </div>
                    <div class="typeName">{{ customData[msgBody.customExts.id]?.typeName }}</div>
                    <div class="info">{{ customData[msgBody.customExts.id]?.content }}</div>
                  </div>
                </div>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="callBackTime(msgBody)" @click="callBackMsg(msgBody)"> 撤回 </el-dropdown-item>
                  <el-dropdown-item @click="deleteMsg(msgBody)"> 删除 </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      <!-- 灰色系统通知 -->
      <template v-if="msgBody.type === CUSTOM_MESSAGE_TYPE.INFORM">
        <div class="inform_style">
          <p>
            {{ msgBody.msg }}
          </p>
        </div>
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.messageList_box {
  width: 100%;
  .message_box_item {
    position: relative;
    display: flex;
    margin: 32px auto;
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
    color: #333333;
    letter-spacing: 0.4px;
    .message_item_time {
      position: absolute;
      top: -25px;
      right: 0;
      left: 0;
      width: 74px;
      height: 20px;
      margin: auto;
      font-size: 10px;
      font-weight: 400;
      line-height: 20px;
      color: #adadad;
    }
    .message_item_avator {
      width: 38px;
      height: 38px;
    }
    .message_box_card {
      display: flex;
      flex-direction: column;
      max-width: 50%;
      min-height: 34px;
    }
    .videoContent {
      display: flex;
      flex-wrap: nowrap;
      justify-content: center;
    }
    .callBack {
      line-height: 40px;
      background: transparent;
      padding-left: 10px;
      padding-right: 10px;
      color: #949494;
    }
    .message_box_nickname {
      margin: 0 10px;
      font-size: 14px;
      line-height: 20px;
      color: #9a9a9a;
      letter-spacing: 0.4px;
    }
    .message_box_content {
      display: flex;
      align-items: center;
      margin: 0 6px;
      word-break: break-all;

      /* 通用音频播放样式 */
      .message_box_content_audio {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        min-width: 80px;
        max-width: 250px;
        font-size: 12px;
        .audio_length_text {
          font-family: Avenir;
          font-size: 12px;
          font-style: normal;
          font-weight: 400;
        }
      }

      /* 对方音频播放样式 */
      .message_box_content_audio_other {
        flex-direction: row;

        @keyframes other_play_icon {
          0% {
            background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_recv_audio02@3x.png")
              no-repeat;
            background-size: 100% 100%;
          }
          50% {
            background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_recv_audio01@3x.png")
              no-repeat;
            background-size: 100% 100%;
          }
          100% {
            background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_recv_audio@3x.png")
              no-repeat;
            background-size: 100% 100%;
          }
        }
        .play_audio_icon_other {
          width: 30px;
          height: 30px;
          margin-right: 10px;
          background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_recv_audio@3x.png")
            no-repeat;
        }
        .start_play_audio {
          animation: other_play_icon 2s;
          animation-iteration-count: infinite;
        }
      }

      /* 己方音频播放样式 */
      .message_box_content_audio_mine {
        flex-direction: row-reverse;

        @keyframes mine_play_icon {
          0% {
            background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_send_audio02@3x.png")
              no-repeat;
            background-size: 100% 100%;
          }
          50% {
            background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_send_audio01@3x.png")
              no-repeat;
            background-size: 100% 100%;
          }
          100% {
            background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_send_audio@3x.png")
              no-repeat;
            background-size: 100% 100%;
          }
        }
        .play_audio_icon_mine {
          width: 30px;
          height: 30px;
          margin-left: 10px;
          background: url("https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/playAudio/msg_send_audio@3x.png")
            no-repeat;
          background-size: 100% 100%;
        }
        .start_play_audio {
          animation: mine_play_icon 2s;
          animation-iteration-count: infinite;
        }
      }
      .txtMsgContent {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        padding: 10px;
        .txtSpan {
          display: flex;
          flex-wrap: nowrap;
        }
        .emojiPng {
          width: 25px;
          height: 25px;
        }
      }

      /* 文件消息样式 */
      .message_box_content_file {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        width: 200px;
        min-height: 60px;
        max-height: 120px;
        padding: 10px;
        .file_text_box {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          width: 75%;
          height: 80%;
          .file_name {
            width: 120px;
            overflow: hidden;
            font-size: 15px;
            font-weight: bold;
            text-overflow: ellipsis;
            white-space: wrap;
          }
          .file_size {
            font-size: 13px;
          }
          .file_download {
            width: 100%;
            font-size: 13px;
            color: #333333;
            cursor: pointer;
            transition: all 0.3s ease;
            &:hover {
              transform: scale(0.9);
            }
          }
        }
        .icon-wenjian {
          font-size: 50px;
          color: #8d8a8a;
        }
      }
      /* 消息状态 */
      .message_item_status {
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        align-items: center;
        position: absolute;
        left: -20px;
        top: 7px;
        .message_item_readed_icon {
          width: 15px;
          height: 15px;
          cursor: pointer;
        }
      }
      /* 自定义消息 */
      .message_box_content_custom {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        min-height: 60px;
        min-width: 200px;
        padding: 10px;
        overflow: hidden;
        .operateBtn {
          margin-top: 8px;
        }
        .type {
          font-size: 17px;
          color: #000;
          font-weight: 700;
          display: flex;
          flex-wrap: nowrap;
          .btn {
            text-align: center;
            font-size: 14px;
            color: #fff;
            font-weight: 400;
            margin-left: 10px;
            padding: 0px 8px;
            line-height: 20px;
            border-radius: 2px;
          }
          .btn1 {
            background-color: #adadad;
          }
          .btn2 {
            background-color: rgb(72, 121, 0);
          }
          .btn3 {
            background-color: red;
          }
        }
        .content {
          .title {
            display: flex;
            justify-content: space-between;
            flex-wrap: nowrap;
            padding-top: 10px;
            font-size: 16px;
            color: #000;
            font-weight: 600;
            .price {
              color: #3e91fa;
              flex-shrink: 0;
              margin-left: 20px;
            }
          }
          .typeName {
            padding: 8px 0;
            .unit {
              color: #3e91fa;
            }
          }
          .info {
            color: #696969;
          }
          .item {
            display: flex;
            flex-wrap: nowrap;
            padding: 5px 0;
            .label {
              margin-right: 10px;
              flex-shrink: 0;
            }
          }
        }
        .user_card_main {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-start;
          font-size: 17px;
          color: #333333;
          .nickname {
            display: inline-block;
            height: 35px;

            // width: 100%;
            margin-left: 10px;
            line-height: 35px;
          }
        }
      }

      /* 个人名片 */
    }
    .message_item_status {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-end;
      .message_item_readed_icon {
        width: 15px;
        height: 15px;
        cursor: pointer;
      }
    }
    .quote_msg_avtive {
      animation: twinkle 0.4s infinite alternate;
    }
    .quote_msg_avtive ::before {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      content: "";
      background-color: rgb(247 169 35 / 50%);
      border-radius: 5px;
    }

    @keyframes twinkle {
      0% {
        opacity: 0.3;
      }
      50% {
        opacity: 0.6;
      }
      100% {
        opacity: 0.9;
      }
    }
    .message_box_content_other {
      background: #ffffff;
      border-radius: 8px 8px 8px 0;
    }
    .noneBg {
      background: transparent;
    }
    .message_box_content_mine {
      background: #c1e3fc;
      border-radius: 8px 0 8px 8px;
    }
  }

  /* 撤回或者系统通知类消息 */
  .recall_style,
  .inform_style {
    height: 60px;
    margin: 5px 0;
    font-size: 10px;
    color: #aaaaaa;
    text-align: center;
    .reEdit {
      margin-left: 3px;
      color: #3e91fa;
      cursor: pointer;
    }
  }
}
.message_quote_box {
  padding: 5px 10px;
  margin-top: 5px;
  font-size: 7px;
  color: #a0a0a0;
  cursor: pointer;
  background-color: #e7e7e7;
  border-radius: 5px;
  p {
    display: -webkit-box;
    overflow: hidden;
    word-break: break-all;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}
:deep(.el-input__wrapper) {
  border-radius: 5px;
}
:deep(.el-dialog__header) {
  margin: 0;
  background: #f2f2f2;
}
</style>
